<?php

namespace app\api\controller;

use app\api\model\User;
use think\App;
use think\facade\Db;

// file_put_contents('ddddd.ddddd', 1222);
define("TOKEN", "weixinweixin");
// $wechatObj = new Wechat();
// $wechatObj->valid();
// $wechatObj->responseMsg();
class Wechat
{

    public function wxapi()
    {
        if (!isset($_GET['echostr'])) {
            $this->responseMsg();
        } else {
            $this->valid();
        }
    }
    //验证签名
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)) {
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            // file_put_contents('dd.d', var_dump($fromUsername));
            $time = time();
            $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
            if ($postObj->MsgType == 'event') {
                $msgType = "text";
                // 通过二维码进入
                if (isset($postObj->EventKey) && $postObj->EventKey != '') {
                   
                    if(strpos($postObj->EventKey,'qrscene_') !== FALSE){
                        // $agent_id = str_replace('qrscene_agent_','', $postObj->EventKey);
                        $scene = explode('_', $postObj->EventKey);
                        $type = $scene[1];
                        $uid = $scene[2];
                    } else {
                        $scene = explode('_', $postObj->EventKey);
                        $type = $scene[0];
                        $uid = $scene[1];
                    }
                    try {
                        $wq = new Wechatqrcode();
                        if ($type == 1) {
                            $U_data = Db::name('user')->where('id', $uid)->field('wx_gzh_openid,nickname')->find();
                            $wx_gzh_openid = $U_data['wx_gzh_openid'];
                            if (empty($wx_gzh_openid)) {
                                Db::name('user')->where('id', $uid)->update(['wx_gzh_openid'=>$fromUsername.""]);
                                $p_data = array(
                                    'first' => array('value' => '微信绑定成功'),
                                    'keyword1' => array('value' => $U_data['nickname']),
                                    'keyword2' => array('value' => '绑定微信成功')
                                );
                                $wq->send_bind_msg($fromUsername, $p_data);
                            }
                        }else if ($type == 2) {
                            $U_data = Db::name('servers_user')->where('id', $uid)->field('name,wx_gzh_openid')->find();
                            $wx_gzh_openid = $U_data['wx_gzh_openid'];
                            if (empty($wx_gzh_openid)) {
                                Db::name('servers_user')->where('id', $uid)->update(['wx_gzh_openid'=>$fromUsername.""]);

                                $p_data = array(
                                    'first' => array('value' => '微信绑定成功'),
                                    'keyword1' => array('value' => empty($U_data['name'])?"服务商":$U_data['name']),
                                    'keyword2' => array('value' => '绑定微信成功')
                                );
                                $wq->send_bind_msg($fromUsername, $p_data);
                                
                            }
                        }else if ($type == 3) {
                            $U_data = Db::name('agent')->where('id', $uid)->field('name,wx_gzh_openid')->find();
                            $wx_gzh_openid = $U_data['wx_gzh_openid'];
                            if (empty($wx_gzh_openid)) {
                                Db::name('agent')->where('id', $uid)->update(['wx_gzh_openid'=>$fromUsername.""]);
                                $p_data = array(
                                    'first' => array('value' => '微信绑定成功'),
                                    'keyword1' => array('value' => empty($U_data['name'])?"代理商":$U_data['name']),
                                    'keyword2' => array('value' => '绑定微信成功')
                                );
                                $wq->send_bind_msg($fromUsername, $p_data);
                            }
                        }
                    } catch (\Throwable $th) {
                    //   file_put_contents('123.l', $th->getMessage());
                    }
                    
                   echo "";
                   exit;
                    // $contentStr = $desc .'---'.'openid:'.$openid.'用户id:'.$uid;
                    // $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $fromUsername);
                    // echo $resultStr;
                }
            }

        } else {
            echo "";
            exit;
        }

    }

    // public function responseMsg()
    // {
    //     //get post data, May be due to the different environments
    //     $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
    //     // file_put_contents('wechat.ddddd', $postStr);
    //     //extract post data
    //     if (!empty($postStr)){
    //             $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
    //             file_put_contents('wechat.ddddd', $postObj);
    //             $fromUsername = $postObj->FromUserName;
    //             $toUsername = $postObj->ToUserName;
    //             $type = $postObj->MsgType;
    //             $customevent = $postObj->Event;
    //             $keyword = trim($postObj->Content);
    //             $time = time();
    //             $textTpl = "<xml>
    //                         <ToUserName><![CDATA[%s]]></ToUserName>
    //                         <FromUserName><![CDATA[%s]]></FromUserName>
    //                         <CreateTime>%s</CreateTime>
    //                         <MsgType><![CDATA[%s]]></MsgType>
    //                         <Content><![CDATA[%s]]></Content>
    //                         <FuncFlag>0</FuncFlag>
    //                         </xml>";
    //             if($type=="event" && $customevent=="subscribe"){
    //                 file_put_contents('ddddd.ddddd', $fromUsername);
    //                 $contentStr = "感谢你的关注\n回复1查看联系方式\n回复2查看最新资讯\n回复3查看法律文书";
    //                 $msgType = "text";
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //                 }
    //             if(!empty( $keyword ))
    //             {
    //                 $msgType = "text";
    //                 if($keyword=="1"){
    //                 $contentStr = "qiphon";}
    //                 if($keyword=="2"){
    //                 $contentStr = "test 。";}
    //                 if($keyword=="3"){
    //                 $contentStr = "test333";}
    //                 file_put_contents('ddddd.ddddd', $fromUsername);
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //             }else{
    //                 echo "Input something...";
    //             }

    //     }else {
    //         echo "";
    //         exit;
    //     }
    // }

    // private function checkSignature()
    // {
    //     $signature = $_GET["signature"];
    //     $timestamp = $_GET["timestamp"];
    //     $nonce = $_GET["nonce"];

    //     $token = TOKEN;
    //     $tmpArr = array($token, $timestamp, $nonce);
    //     sort($tmpArr);
    //     $tmpStr = implode('',$tmpArr );
    //     $tmpStr = sha1( $tmpStr );

    //     if( $tmpStr == $signature ){
    //         return true;
    //     }else{
    //         return false;
    //     }
    // }

}
